<?php

class Model_auth extends CI_Model {
	
	public function get_proximity($long,$lat) {
		$sql = 'select a.*, IFNULL(c.cost,0) as cost 
				from authorizations a left join costs c on a.id=c.auth_id 
									left join cost_types ct on c.type_id=ct.id 
				where (a.x_coord between '.($lat-0.02).' and '.($lat+0.02).') and 
				(y_coord between '.($long-0.04).' and '.($long+0.04).' ) and 
				( ct.name="Cost ora" or ct.name IS NULL) and 
				((hour(CURRENT_TIME()) between a.start_hour and a.end_hour) or (ifnull(a.start_hour,0)=0 and ifnull(a.end_hour,0)=0))';
		$query = $this->db->query($sql);
		return $query->result_array();
	}
	
	
	
	public function get_user_auth($uid) {
		$query = $this->db->query('select * from authorizations where user_id="'.$uid.'"');
		return $query->result_array();
	}
	
	public function add_auth($uid,$utype) {
		
		$data = array (
				'auth_no' => $this->input->post('auth_no'),
				'user_id' => $uid,
				'valability' => $this->input->post('valability'),
				'total' => $this->input->post('total'),
				'available' => $this->input->post('total'),
				'start_hour' => $this->input->post('ora_start'),
				'end_hour' => $this->input->post('ora_end'),
				'x_coord' => $this->input->post('lat'),
				'y_coord' => $this->input->post('long')
		);
		
		if($utype==0) {
			$data['total'] = 1;
			$data['available'] = 1;
		} elseif($utype==1) {
			$data['total'] = $this->input->post('total');
			$data['available'] = $this->input->post('total');
		}
		
		$upload=$this->upload->data();
		if($upload['orig_name']!='') {
			$data['file_name']=$upload['orig_name'];
		}
		
		$query = $this->db->insert('authorizations', $data);
		var_dump($query);
		if($query) {
			return true;
		} else {
			return false;
		}
	}
}